import uuid
from src.common.logger import getLogger
from src.modules.memory.dao import MemoryDetailDao

logger = getLogger()

def load_memory_details(args):
    logger.info(f"load_memory_detail args: {args}")
    list = MemoryDetailDao.load_memory_details(args)
    return list

def insert_memory_detail_user(form):
    from ..model.memory_detail import MemoryDetail

    memory_detail_user = MemoryDetail()
    memory_detail_user.id = uuid.uuid4()
    memory_detail_user.source_id = form.get("source_id")
    memory_detail_user.type = "user"
    memory_detail_user.content = form.get("query")
    MemoryDetailDao.insert_memory_detail(memory_detail_user)

def insert_memory_detail_ai(form, retrieve_result):
    from ..model.memory_detail import MemoryDetail

    memory_detail_ai = MemoryDetail()
    memory_detail_ai.id = uuid.uuid4()
    memory_detail_ai.source_id = form.get("source_id")
    memory_detail_ai.type = "ai"
    memory_detail_ai.content = retrieve_result.get("chain_result")
    MemoryDetailDao.insert_memory_detail(memory_detail_ai)

def delete_memory_detail(id):
    MemoryDetailDao.delete_memory_detail(id)

def download_memory_detail(args):
    content = ""
    list = load_memory_details(args)
    logger.info(f"download_memory_detail list len: {len(list)}")
    for detail in list:
        if "user" == detail["type"]:
            content += "\n\n\n" if content else ""
            content += "## user\n"
        else:
            content += "\n\n## assistant\n"
        content += detail["content"]
    logger.info(f"download_memory_detail content len: {len(content)}")
    return content
